//后端地址
const backend_url = "http://localhost:8080/"
//文件树api地址
const folder_url = "api/folders/listFolders?path"
//混淆方法api地址
const obfuscate_url = "api/obfuscate/startObfuscation"
const init_url = "api/folders/watermark"
//背景水印
async function watermark() {
    var url = backend_url + init_url
    const resp = await fetch(url);
    const data = await resp.json();
    const text1 = data.text1;
    const text2 = data.text2;
    const angle = -20 * Math.PI / 180;
    const canvas = document.createElement('canvas');
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;
    canvas.width = screenWidth;
    canvas.height = screenHeight;
    const ctx = canvas.getContext('2d');

    ctx.clearRect(0, 0, screenWidth, screenHeight);
    ctx.fillStyle = 'rgba(0,0,0,0.05)';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = '20px sans-serif';

    const cellWidth = 195; // 网格宽度
    const cellHeight = 140; // 网格高度

    // 遍历网格，每个格子里随机放一个水印
    for (let x = 0; x < screenWidth; x += cellWidth) {
        for (let y = 0; y < screenHeight; y += cellHeight) {
            const offsetX = (Math.random() - 0.5) * cellWidth * 0.5;
            const offsetY = (Math.random() - 0.5) * cellHeight * 0.5;
            ctx.save();
            ctx.translate(x + offsetX, y + offsetY);
            ctx.rotate(angle);
            ctx.fillText(text1, 0, -10);
            ctx.fillText(text2, 0, 20);
            ctx.restore();
        }
    }

    const watermarkLayer = document.createElement('div');
    watermarkLayer.style.position = 'fixed';
    watermarkLayer.style.top = '0';
    watermarkLayer.style.left = '0';
    watermarkLayer.style.width = '100%';
    watermarkLayer.style.height = '100%';
    watermarkLayer.style.pointerEvents = 'none';
    watermarkLayer.style.backgroundImage = `url(${canvas.toDataURL('image/png')})`;
    watermarkLayer.style.backgroundRepeat = 'repeat';
    watermarkLayer.style.zIndex = '9999';
    document.body.appendChild(watermarkLayer);
}
//清空所有配置
const clear = (vm) => {
    vm.displayPath = '';
    vm.commonBasePackage = '';
    vm.projectType = 'JAVA_PROJECT';
    vm.folders = [];
    vm.selectedFolders = [];
    vm.selectedObfuscators = [];
    vm.selectedOptionalObfuscators = [];
    vm.activeCollapses = [];
    vm.activeOptionalCollapses = [];

    // 核心混淆器配置重置
    vm.renameClassConfig = {
        renameReferencedClass: true,
        packageList: []
    };
    vm.renameFieldConfig = {
        basePackage: '',
        packageList: []
    };
    vm.renameMethodConfig = {
        isReferenceMethodOnly: false,
        basePackage: '',
        packageList: []
    };
    vm.methodArgumentConfig = {
        basePackage: '',
        isReferenceMethodOnly: false,
        minAddParamNum: 1,
        maxAddParamNum: 3,
        packageList: []
    };
    vm.interfaceMethodArgumentConfig = {
        basePackage: '',
        minAddParamNum: 1,
        maxAddParamNum: 3
    };
    vm.randomRenamePkgConfig = {
        basePackage: '',
        packageList: []
    };
    vm.classRandomShuffleConfig = {
        basePackage: '',
        packageList: []
    };
    // 可选混淆器配置重置
    vm.md5Config = {
        md5Type: 'AUDIO',
        packageList: [],
        md5TargetPath: ''
    };
    vm.renamePackageConfig = {
        resourceRoot: '',
        delOldFiles: false,
        packageList: [],
        targetPackagesInput: ''
    };
    vm.androidResConfig = {
        sourceRoot: '',
        packageList: [],
        resourceOldPrefixInput: '',
        resourceNewPrefixInput: ''
    };
    vm.mnnConfig = {
        modelPath: "",
        installType: "PIP",
        sourceCodeInstallPath: "",
        forward: true,
        tempPath: "",
        modelNames: ""
    };

    ElementPlus.ElMessage.success('已清空所有配置');
}

// 自定义文件树子组件开始
const FolderNode = {
    name: 'FolderNode',
    props: { node: Object, selected: Array },
    emits: ['update:selected'],
    data() { return { expanded: false }; },
    computed: {
        isSelected() {
            const sel = Array.isArray(this.selected) ? this.selected : [];
            if (sel.includes(this.node.path)) return true;
            if (this.node.children && this.node.children.length) {
                return this.node.children.some(child =>
                    sel.includes(child.path) || (child.children && child.children.length && this.hasSelectedDescendant(child))
                );
            }
            return false;
        }
    },
    methods: {
        hasSelectedDescendant(node) {
            const sel = Array.isArray(this.selected) ? this.selected : [];
            if (!node.children || !node.children.length) return false;
            return node.children.some(c =>
                sel.includes(c.path) || (c.children && c.children.length && this.hasSelectedDescendant(c))
            );
        },
        toggleExpand() { this.expanded = !this.expanded; },
        toggleSelect(val) {
            const sel = Array.isArray(this.selected) ? [...this.selected] : [];
            const path = this.node.path;
            if (val) {
                const filtered = sel.filter(p =>
                    !(p.startsWith(path + '/')) && !(path.startsWith(p + '/'))
                );
                filtered.push(path);
                this.$emit('update:selected', filtered);
            } else {
                const filtered = sel.filter(p => p !== path);
                this.$emit('update:selected', filtered);
            }
        },
        forwardUpdate(updated) { this.$emit('update:selected', updated); }
    },
    template: `
<div>
  <el-checkbox
    class="folder-checkbox"
    :label="node.path"
    :model-value="isSelected"
    @change="toggleSelect"
  >
    <template #default>
      <span
        v-if="node.children && node.children.length"
        class="folder-icon"
        tabindex="0"
        role="button"
        @click.stop.prevent="toggleExpand"
        @pointerdown.stop.prevent
        @mousedown.stop.prevent
        @keydown.enter.stop.prevent="toggleExpand"
      >{{ expanded ? '−' : '+' }}</span>
      <span v-else class="folder-icon placeholder">•</span>
      <span class="folder-label">{{ node.name }}</span>
    </template>
  </el-checkbox>

  <div v-if="expanded && node.children && node.children.length" class="folder-children">
    <folder-node
      v-for="child in node.children"
      :key="child.path"
      :node="child"
      :selected="selected"
      @update:selected="forwardUpdate"
    ></folder-node>
  </div>
</div>
`
};
// 自定义文件树子组件结束


//加载文件夹树方法
const loadTree = (path, vm) => {
    var load_folder_url = backend_url + folder_url
    fetch(`${load_folder_url}=${encodeURIComponent(path)}`)
        .then(async res => {
            const data = await res.json().catch(() => null);
            if (!res.ok) {
                throw new Error(data?.message || `HTTP ${res.status}`);
            }
            return data;
        })
        .then(data => {
            vm.folders = data;
            vm.selectedFolders = [];
            if (!data.length) {
                ElMessage.info('未检测到子文件夹');
            } else {
                ElMessage.success('已加载文件夹树');
            }
        })
        .catch(err => {
            ElMessage.error(err.message);
        });
}
//混淆方法
const obfuscate = (payload) => {
    var start_obfuscate = backend_url + obfuscate_url
    fetch(`${start_obfuscate}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    }).then(async res => {
        const data = await res.json().catch(() => null);
        if (!res.ok) {
            throw new Error(data?.message || `HTTP ${res.status}`);
        }
        return data;
    }).then(data => {
        ElMessage.success(data.data);
    }).catch(err => {
        ElMessage.error(err.message);
    });
}


//  fetch('http://localhost:8080/api/obfuscate/startObfuscation', {
//                         method: 'POST',
//                         headers: {
//                             'Content-Type': 'application/json'
//                         },
//                         body: JSON.stringify(payload)
//                     })
//                         .then(async res => {
//                             const data = await res.json().catch(() => null);
//                             if (!res.ok) {
//                                 throw new Error(data?.message || `HTTP ${res.status}`);
//                             }
//                             return data;
//                         })
//                         .then(data => {
//                             ElMessage.success(data.data);
//                         })
//                         .catch(err => {
//                             ElMessage.error(err.message);
//                         });


// fetch(`http://localhost:8080/api/folders/get?path=${encodeURIComponent(this.displayPath)}`)
//     .then(async res => {
//         const data = await res.json().catch(() => null);
//         if (!res.ok) {
//             throw new Error(data?.message || `HTTP ${res.status}`);
//         }
//         return data;
//     })
//     .then(data => {
//         this.folders = data;
//         this.selectedFolders = [];
//         if (!data.length) {
//             ElMessage.info('未检测到子文件夹');
//         } else {
//             ElMessage.success('已加载文件夹树');
//         }
//     })
//     .catch(err => {
//         ElMessage.error(err.message);
//     });

// <!-- <script src="https://unpkg.com/vue@3/dist/vsue.global.prod.js"></script> -->
// <!-- <script src="https://unpkg.com/element-plus/dist/index.full.js"></script> -->
//核心混淆器的复选框选择混淆功能的名称
// toggleObfuscatorSelection(name, checked) {
//     if (checked) {
//         if (!this.selectedObfuscators.includes(name)) {
//             this.selectedObfuscators.push(name);
//         }
//     } else {
//         this.selectedObfuscators = this.selectedObfuscators.filter(n => n !== name);
//     }
// },
//可选混淆器的复选框选择混淆功能的名称
// toggleOptionalObfuscatorSelection(name, checked) {
//     if (checked) {
//         if (!this.selectedOptionalObfuscators.includes(name)) {
//             this.selectedOptionalObfuscators.push(name);
//         }
//     } else {
//         this.selectedOptionalObfuscators = this.selectedOptionalObfuscators.filter(n => n !== name);
//     }
// },
// //重命名字段名混淆器移除包按钮
// removeFieldPackage(pkg) {
//     const pathFormat = pkg.replace(/\./g, '/');
//     this.renameFieldConfig.packageList = this.renameFieldConfig.packageList.filter(p => p !== pkg);
//     this.selectedFolders = this.selectedFolders.filter(p => !p.endsWith(pathFormat));
// },
// //重命名方法名混淆器移除包按钮
// removeMethodPackage(pkg) {
//     const pathFormat = pkg.replace(/\./g, '/');
//     this.renameMethodConfig.packageList = this.renameMethodConfig.packageList.filter(p => p !== pkg);
//     this.selectedFolders = this.selectedFolders.filter(p => !p.endsWith(pathFormat));
// },
// //普通方法参数混淆器移除包按钮
// removeMethodArgumentPackage(pkg) {
//     const pathFormat = pkg.replace(/\./g, '/');
//     this.methodArgumentConfig.packageList = this.methodArgumentConfig.packageList.filter(p => p !== pkg);
//     this.selectedFolders = this.selectedFolders.filter(p => !p.endsWith(pathFormat));
// },
// removeMd5Package(pkg) {
//     // this.md5Config.md5PackageList = this.md5Config.md5PackageList.filter(p => p !== pkg);

//     this.md5Config.packageList = this.md5Config.packageList.filter(p => p !== pkg);
//     const path = pkg.replace(/\./g, '/');
//     this.selectedFolders = this.selectedFolders.filter(p => p !== path);
// },
// removeRenameSourcePackage(pkg) {

//     // this.renamePackageConfig.sourcePackages = this.renamePackageConfig.sourcePackages.filter(p => p !== pkg);

//     this.renamePackageConfig.packageList = this.renamePackageConfig.packageList.filter(p => p !== pkg);
//     const path = pkg.replace(/\./g, '/');
//     this.selectedFolders = this.selectedFolders.filter(p => p !== path);
// },